open(SAMP,"Sample_mapping_merge.fam") or die "no file exists merge.fam\n";
open(WRBUFF,">Duplicates");
open(WRREPLACE,">Replace");
while(<SAMP>)
{
	chomp($_);
	@samp=split(" ",$_);
	$samp{$samp[1]}=$_;
}
open(PLINK,"Sample_mapping_merge.genome") or die "no file found plink.genome\n";
#$line=<PLINK>;
$val=0;
$k1=0;
$k2=0;
$k3=0;
$k4=0;
while($line=<PLINK>)
{
	chomp($line);
	$line =~ s/^\s+//g;
	@array=split(/\s+/,$line);
	#print $array[1]."\t".$array[3]."\t".$array[9]."\n";
	if($array[9] >0.9)
	{
		if(exists($hash{$array[1]}) && exists($hash{$array[3]}))
		{
			$k1++;
			#die "$array[1]  $hash{$array[1]} $array[3] $hash{$array[3]} already exists\n";
		}
		elsif(exists($hash{$array[1]}))
		{
			$k2++;
			$hash{$array[3]} = $hash{$array[1]};
		}
		elsif(exists($hash{$array[3]}))
		{
			$k3++;
			$hash{$array[1]} =$hash{$array[3]};
		}
		else
		{
			$k4++;
			$val++;
			$hash{$array[1]} = $val;
			$hash{$array[3]} = $val;	
		}
		#print WRBUFF "$array[1] $hash{$array[1]}\n$array[3] $hash{$array[3]}\n";
	}
}
#print "size of hash:  " . keys( %hash ) . " $k1 $k2 $k3 $k4\n";
$prev=-1;
$pp="";
undef(@array);
foreach $key (sort {$hash{$a} <=> $hash{$b} } keys %hash)
{     
	#print "$key  $hash{$key}\n";
	if( $prev == $hash{$key})
	{
		##print  WRBUFF "\t$key";
		#print  WRBUFF $samp{$key}."\n";
		#print WRREPLACE $pp."\n";
		push(@array,$key);
	}
	else
	{
		if($prev != -1)
		{
			##print  WRBUFF "\n";
			@array=sort {$b <=> $a } @array;
			$final{$prev}=join("\t",@array);
			undef(@array);
		}
		push(@array,$key);
		#print  "$hash{$key}\t$key";
		#$pp=$samp{$key};
	}	
	$prev=$hash{$key};
}
@array=sort {$b <=> $a } @array;
$final{$prev}=join("\t",@array);;
undef(@array);
foreach $key (sort {$a <=> $b } keys %final)
{
	@array=split("\t",$final{$key});
	for($i=1;$i<@array;$i++)
	{
		print WRREPLACE $samp{$array[0]}."\n";
		print  WRBUFF $samp{$array[$i]}."\n";
	}
	print "$key $final{$key}\n";
}
